package utils

import (
	"log"
	"time"

	"github.com/dgrijalva/jwt-go"
)

var MySignKey = []byte("!@#qwe")

type MyClaim struct {
	ID    int    `json:"id"`
	Phone string `json:"phone"`
	jwt.StandardClaims
}

// 生成Token
func MakeToken(id int, phone string) string {
	log.Print("id========", id)
	c := MyClaim{
		ID:    id,
		Phone: phone,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix(),           // JWT生效时间
			ExpiresAt: time.Now().Unix() + 1200000, // JWT过期时间
		},
	}
	// 返回未加密signatrue
	sensitiveToken := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
	//利用secret签名对token加密
	token, err := sensitiveToken.SignedString(MySignKey)
	if err != nil {
		return ""
	}
	return token
}

// 解析token
func CheckToken(token string) (*MyClaim, error) {
	log.Print("jwt--token====", token)
	var user MyClaim
	tokenObj, err := jwt.ParseWithClaims(token, &user, func(token *jwt.Token) (i interface{}, err error) {
		return MySignKey, nil
	})
	if err != nil || !tokenObj.Valid {
		return nil, err
	}
	return &user, nil
}
